//
//  CoreDataManager.m
//  LOL视频播放
//
//  Created by 花花蔡 on 2016/12/13.
//  Copyright © 2016年 com.HuaHuaCai. All rights reserved.
//

#import "CoreDataManager.h"
//数据库表名
#define ENTITY_NAME @"Model"
@implementation CoreDataManager

+ (instancetype)manager {
    static CoreDataManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CoreDataManager alloc] init];
    });
    return manager;
}

-(BOOL)addDataWithPictureName:(NSString *)picture Title:(NSString *)title Date:(NSString *)date Count:(NSString *)count VideoURStr:(NSString *)url {
    //将模型转换为数据库实体模型对象
    Model *model = [NSEntityDescription insertNewObjectForEntityForName:ENTITY_NAME inManagedObjectContext:self.context];
    
    model.count = count;
    model.picture = picture;
    model.title = title;
    model.date = date;
    model.url = url;
    
    NSLog(@"%@----%@---%@----%@- %@",model.picture,model.title,model.date,model.url,model.count);
    NSError *error = nil;
    BOOL isSave = [self.context save:&error];
    
    return isSave;
    
}

- (NSArray *)searchData {
    
    //获取查询对象
    NSFetchRequest *request = [Model fetchRequest];
    NSArray *searchData = [self.context executeFetchRequest:request error:nil];
    return searchData;
}

- (void)deleteForDataWithModel:(Model *)model {
    
    NSString *title = model.title;
    NSString *count = model.count;
    NSString *date = model.date;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title==%@ &&count==%@ && date==%@",title,count,date];
    NSFetchRequest *request = [Model fetchRequest];
    request.predicate = predicate;
    
    NSArray *searchData = [self.context executeFetchRequest:request error:nil ];
    
    for (Model *model in searchData) {
        [self.context deleteObject:model];
        //        NSLog(@"%@-----%@-----%@---%@",model.title,model.count,model.date,model.url);
    }
    [self.context save:nil];
}

#pragma mark - 懒加载
- (NSManagedObjectContext *)context {
    
    if (!_context) {
        //配置容器
        NSPersistentContainer *container = [NSPersistentContainer persistentContainerWithName:@"HistoryModel"];
        //初始化
        [container loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription * description, NSError * error) {
            //
        }];
        _context = container.viewContext;
    }
    return _context;
}


@end
